# -*- coding: utf-8 -*-
"""
Author: chen xi
Date: 2025/6/26 下午5:05
File: log_uploader.py
"""

import requests
import os


def upload_log_file(file_path, server_url="http://192.168.250.79:5557", timeout=10):
	"""
	上传日志文件到指定的 Web 服务接口，并返回下载链接

	:param file_path: str, 要上传的文件路径（本地）
	:param server_url: str, 服务地址（如 http://xrsdev.tpddns.cn:5557）
	:param timeout: int, 请求超时时间（秒）
	:return: dict, 包含 filename 和 download_url 或 error
	"""
	
	if not os.path.isfile(file_path):
		return {"error": f"File not found: {file_path}"}
	
	upload_url = f"{server_url.rstrip('/')}/upload"
	
	try:
		with open(file_path, "rb") as f:
			files = {"file": f}
			response = requests.post(upload_url, files=files, timeout=timeout)
		
		if response.status_code == 200:
			try:
				result = response.json()
				filename = result.get("filename")
				if filename:
					download_url = f"{server_url.rstrip('/')}/download/{filename}"
					result["download_url"] = download_url
				return result
			except requests.exceptions.JSONDecodeError:
				return {"error": "Invalid response format (not JSON)", "raw": response.text}
		else:
			try:
				return response.json()
			except requests.exceptions.JSONDecodeError:
				return {
					"error": "Upload failed",
					"status_code": response.status_code,
					"response_text": response.text
				}
	
	except requests.exceptions.RequestException as e:
		return {"error": f"Network error: {str(e)}"}


if __name__ == "__main__":
	result = upload_log_file("./logs/filtered_log.zip", server_url="http://192.168.250.79:5557/")
	print(result)
	if "error" in result:
		print(f"❌ 上传失败: {result['error']}")
	else:
		print(f"✅ 上传成功！服务器保存的文件名: {result['filename']}")
